<template>
  <div>
    <h1>课程管理</h1>
    <el-button @click="addCourseButtonClick">添加课程</el-button>
    <el-table 
      :row-key="(row: any) => row.courseId"
      :default-sort="{ prop: 'courseName', order: 'ascending' }"
      :data="courseStore.courses" stripe>
      <el-table-column prop="courseName" label="课程名称" sortable ></el-table-column>
      <el-table-column prop="courseId" label="课程代码" sortable ></el-table-column>
      <el-table-column prop="credits" label="学分" sortable ></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="editCourse(scope.$index)">编辑</el-button>
          <el-button @click="deleteCourse(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="courseStore.currentPage"
      :page-size="courseStore.pageSize"
      :total="courseStore.total"
      @current-change="handleCurrentChange"
      layout="total, prev, pager, next"
    />
    <el-dialog  v-model="addCourseModal" title="添加课程">
        <el-form :model="courseForm" :rules="rules" ref="courseFormRef" label-width="100px">
          <el-form-item label="课程 ID" prop="courseId">
            <el-input v-model="courseForm.courseId" :disabled="isEditing"></el-input>
          </el-form-item>
          <el-form-item label="课程名称" prop="courseName">
            <el-input v-model="courseForm.courseName"></el-input>
          </el-form-item>
          <el-form-item label="课程描述" prop="courseDescription">
            <el-input v-model="courseForm.courseDescription" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="学分" prop="credits">
            <el-input v-model.number="courseForm.credits"></el-input>
          </el-form-item>
          <el-form-item label="前置课程ID" prop="preCourseId">
            <el-input v-model.string="courseForm.preCourseId"></el-input>
          </el-form-item>
        </el-form>
      <template #footer>
        <el-button @click="addCourseModal = false; isEditing = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, reactive } from 'vue';
import { useCourseStore } from '../stores/course';
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElPagination } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'

const courseStore = useCourseStore();
const addCourseModal = ref(false);
const isEditing = ref(false); // 标记是否处于编辑状态
const currentEditIndex = ref(-1); // 记录当前编辑条目的索引

const courseForm = ref({
  courseId: '',
  courseName: '',
  courseDescription: '',
  credits: 0,
  preCourseId: ''
});

const rules = reactive<FormRules<typeof courseForm>>({
  courseId: [
    { required: true, message: '请输入课程 ID', trigger: 'blur' }
  ],
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  courseDescription: [
    { required: true, message: '请输入课程描述', trigger: 'blur' }
  ],
  credits: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    { type: 'number', message: '学分必须为数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== null && value !== undefined &&!Number.isInteger(value)) {
          callback(new Error('学分必须为小数'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ],
  preCourseId: [
    { type: 'string', message: '前置课程ID需要去之前的课程ID对应', trigger: 'blur' }
  ]
});

const courseFormRef = ref<FormInstance>();

const addCourseButtonClick = () => {
  addCourseModal.value = true;
  isEditing.value = false;
  courseForm.value = {
    courseId: '',
    courseName: '',
    courseDescription: '',
    credits: 0,
    preCourseId: ''
  };
};

const editCourse = (index: number) => {
  isEditing.value = true;
  currentEditIndex.value = index;
  addCourseModal.value = true;
  // 将选中条目的信息回显到对话框中
  courseForm.value = { ...courseStore.courses[index] };
};

const submitForm = async () => {
  await nextTick();
  courseFormRef.value?.validate(async (valid) => {
    if (valid) {
      if (isEditing.value) {
        // 更新课程信息
        await courseStore.updateCourse(currentEditIndex.value, courseForm.value);
      } else {
        await courseStore.addCourse(courseForm.value);
      }
      addCourseModal.value = false;
      isEditing.value = false;
      courseForm.value = {
        courseId: '',
        courseName: '',
        courseDescription: '',
        credits: 0,
        preCourseId: ''
      };
    }
  });
};

const deleteCourse = (index: number) => {
  courseStore.deleteCourse(index);
};

const handleCurrentChange = (page: number) => {
  courseStore.changePage(page);
};

onMounted(() => {
  // 页面加载时的操作
});
</script>

<style scoped>
/* 可根据需要添加一些样式 */
</style>